package com.mspbots.rule.queue.producer;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.api.client.CoreClient;
import com.mspbots.api.service.TenantTicketService;
import com.mspbots.cw.request.TenantDTO;
import com.mspbots.cw.request.TenantTicketDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

/**
 * @ClassName com.mspbots.rule.queue.producer.MessageProducer
 * @Description TODO
 * @Author Jun
 * @Date 2019/8/28 15:53
 * @Version 1.0
 **/
@Slf4j
@Component
public class TicketProducer {

    @Autowired
    TenantTicketService tenantTicketService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitMessagingTemplate messagingTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private CoreClient coreClient;

    //    @Scheduled(cron = "0 0/1 * * * *")
    public void produce() {
        log.info("TicketProducer...");
        Map<String, Object> tenantParams = Map.of("statusId", 1);
        JsonNode tenantNode = coreClient.get("/tenant/list", tenantParams).block();
        List<TenantDTO> list = objectMapper.convertValue(tenantNode, new TypeReference<List<TenantDTO>>() {
        });
        for (TenantDTO tenantDTO : list) {
            Map<String, Object> ticketsParams = Map.of("tenantId", tenantDTO.getId(),
                    "updatedTimeStart", LocalDateTime.of(LocalDate.now(), LocalTime.MIN),
                    "ownerNull", true);
            List<TenantTicketDTO> ticketDTOList = tenantTicketService.findList(ticketsParams);

            if (!CollectionUtils.isEmpty(ticketDTOList)) {
                log.info("tenant {} ticket size {}", tenantDTO.getId(), ticketDTOList.size());
                ticketDTOList.stream().parallel().forEach(item -> this.messagingTemplate.convertAndSend("msp.trigger.tickets", "", item));
            } else {
                log.info("tenant {} ticket size 0", tenantDTO.getId());
            }
        }
    }

}
